<template>
	<div>
		<template v-if="formConf.popupType === 'general' && dialogLoading">
			<Dialog
				:visible.sync="visible"
				:title="!dataForm.id ? '新建' : '编辑'"
				:close-on-click-modal="false"
				class="m-view-dialog m-view-dialog_center"
				lock-scroll
				:width="formConf.generalWidth"
				@close="goBack()"
			>
				<Parser
					v-if="!loading"
					:key="key"
					ref="dynamicForm"
					:data="formConf"
					@submit="submitForm"
				/>
				<template #footer>
					<span
						class="dialog-footer"
					>
						<div
							v-if="dataForm.id && showMoreBtn"
							class="previous-button"
						>
							<Button
								:disabled="prevDis"
								@click="prev"
							>
								{{"上一条"}}
							</Button>
							<Button
								:disabled="nextDis"
								@click="next"
							>
								{{"下一条"}}
							</Button>
						</div>
						<template
							v-if="formConf.hasPrintBtn && formConf.printId && dataForm.id && false"
						>
							<Button
								type="primary"
								@click="print"
							>
								{{formConf.printButtonText || "打 印"}}
							</Button>
						</template>
						<Button @click="goBack">{{formConf.cancelButtonText || "取 消"}}</Button>
						<Button
							type="primary"
							:loading="btnLoading"
							:disabled="continueBtnLoading"
							@click="dataFormSubmit()"
						>
							{{formConf.confirmButtonText || "确 定"}}</Button>
						<Button
							v-if="!dataForm.id || type != 5"
							type="primary"
							:loading="continueBtnLoading"
							:disabled="btnLoading"
							@click="dataFormSubmit(2)"
						>
							{{!dataForm.id ? "确定并新增" : "确定并继续"}}</Button>
					</span>
				</template>
			</Dialog>
		</template>
		<template v-if="formConf.popupType === 'fullScreen'">
			<transition name="el-zoom-in-center">
				<div class="m-view-preview-main">
					<div class="m-view-common-page-header">
						<PageHeader
							:content="!dataForm.id ? '新建' : '编辑'"
							@back="goBack"
						/>
						<div class="m-view-options">
							<Dropdown
								class="dropdown"
								placement="bottom"
							>
								<Button
									style="width: 70px"
									:disabled="continueBtnLoading"
								>
									更 多<i class="el-icon-arrow-down el-icon--right"/>
								</Button>
								<template #dropdown>
									<DropdownMenu>
										<template v-if="dataForm.id && showMoreBtn">
											<DropdownItem
												:disabled="prevDis"
												@click.native="prev"
											>
												{{"上一条"}}
											</DropdownItem>
											<DropdownItem
												:disabled="nextDis"
												@click.native="next"
											>
												{{"下一条"}}
											</DropdownItem>
										</template>
										<DropdownItem
											v-if="!dataForm.id || type != 5"
											type="primary"
											:loading="continueBtnLoading"
											:disabled="btnLoading"
											@click.native="dataFormSubmit(2)"
										>
											{{!dataForm.id ? "确定并新增" : "确定并继续"}}
										</DropdownItem>
									</DropdownMenu>
								</template>
							</Dropdown>
							<template
								v-if="
									formConf.hasPrintBtn && formConf.printId && dataForm.id && false
								"
							>
								<Button
									type="primary"
									@click="print"
								>
									{{formConf.printButtonText || "打 印"}}
								</Button>
							</template>
							<Button
								type="primary"
								:loading="btnLoading"
								:disabled="continueBtnLoading"
								@click="dataFormSubmit()"
							>
								{{formConf.confirmButtonText || "确 定"}}
							</Button>
							<Button
								:disabled="continueBtnLoading"
								@click="goBack"
							>
								{{formConf.cancelButtonText || "取 消"}}
							</Button>
						</div>
					</div>
					<div
						v-if="!loading"
						class="m-view-dynamic-form-main"
						:style="{ margin: '0 auto', width: formConf.fullScreenWidth }"
					>
						<Parser
							:key="key"
							ref="dynamicForm"
							:data="formConf"
							@submit="submitForm"
						/>
					</div>
				</div>
			</transition>
		</template>
		<template v-if="formConf.popupType === 'drawer'">
			<Drawer
				:visible.sync="visible"
				:title="!dataForm.id ? '新建' : '编辑'"
				:wrapper-closable="false"
				:size="formConf.drawerWidth"
				:append-to-body="true"
				class="m-view-common-drawer"
				@close="goBack()"
			>
				<div class="m-view-flex-main">
					<div class="dynamicForm">
						<Parser
							v-if="!loading"
							:key="key"
							ref="dynamicForm"
							:data="formConf"
							@submit="submitForm"
						/>
					</div>
					<div class="drawer-footer">
						<div
							v-if="dataForm.id && showMoreBtn"
							class="previous-button"
						>
							<Button
								:disabled="prevDis"
								@click="prev"
							>
								{{"上一条"}}
							</Button>
							<Button
								:disabled="nextDis"
								@click="next"
							>
								{{"下一条"}}
							</Button>
						</div>
						<template
							v-if="formConf.hasPrintBtn && formConf.printId && dataForm.id && false"
						>
							<Button
								type="primary"
								@click="print"
							>
								{{formConf.printButtonText || "打 印"}}
							</Button>
						</template>
						<Button @click="goBack()">
							{{formConf.cancelButtonText || "取 消"}}
						</Button>
						<Button
							type="primary"
							:loading="btnLoading"
							:disabled="continueBtnLoading"
							@click="dataFormSubmit()"
						>
							{{formConf.confirmButtonText || "确 定"}}
						</Button>
						<Button
							v-if="!dataForm.id || type != 5"
							type="primary"
							:loading="continueBtnLoading"
							:disabled="btnLoading"
							@click="dataFormSubmit(2)"
						>
							{{!dataForm.id ? "确定并新增" : "确定并继续"}}
						</Button>
					</div>
				</div>
			</Drawer>
		</template>
		<!-- <PrintDialog v-if="printDialogVisible" ref="printDialog" @change="printBrowseHandle">
        </PrintDialog> -->
		<!-- <PrintBrowse :id="printId" :visible.sync.sync="printBrowseVisible" :formId="dataForm.id" /> -->
	</div>
</template>

<script>
import {Dialog,Button,Dropdown,DropdownMenu,DropdownItem,Drawer,PageHeader} from 'element-ui';
import {toDate, cloneDeep} from '../../utils/index.js';
import dayjs from 'dayjs';
import Parser from '../../../form-render';
import {magic} from '@lexmis/magic-ui/pc';
/* ⬇️ 未迁移功能 ⬇️*/
// import PrintDialog from "@/components/PrintDialog";
// import {createModel, updateModel, getModelInfo} from '@/api/onlineDev/visualDev';
// import Parser from '../../../../magic-form-render/src/index.ts';
// import PrintBrowse from "@/components/PrintBrowse";
export default {
	components:{
		Parser,
		Dialog,
		Button,
		Dropdown,
		DropdownMenu,
		DropdownItem,
		Drawer,
		PageHeader
    // PrintBrowse,
    // PrintDialog
	},
	data(){
		return {
			printId:'',
			printDialogVisible:false,
			visible:false,
			key:+new Date(),
			formConf:{},
			dataForm:{
				id:'',
				templateId:'',
				data:'',
			},
			modelId:'',
			formData:{},
			btnLoading:false,
			loading:true,
			isPreview:false,
			useFormPermission:false,
			printBrowseVisible:false,
			formOperates:[],
			dialogLoading:false,
			continueBtnLoading:false,
			index:0,
			prevDis:false,
			nextDis:false,
			allList:[],
			showMoreBtn:true,
			type:1,
			refreshDataList:false,
		};
	},
	methods:{
		goBack(){
			this.destroyStyle();
			this.visible = false;
			this.$emit('refresh-data-list', this.refreshDataList);
		},
		printBrowseHandle(id){
			this.printDialogVisible = false;
			this.printId = id;
			this.printBrowseVisible = true;
		},
		print(){
			if(this.isPreview){
				return this.$message({message:'功能预览不支持打印', type:'warning'});
			}
			this.printDialogVisible = true;
			this.$nextTick(() => {
				if(this.formConf.printId.length > 1){
					this.$refs.printDialog.init(this.formConf.printId);
					return;
				}
				this.printBrowseHandle(this.formConf.printId);
			});
		},
		init(formConf, modelId, id, isPreview, useFormPermission, allList, type){
			this.formConf = cloneDeep(formConf);
			this.modelId = modelId;
			this.isPreview = isPreview;
			this.useFormPermission = useFormPermission;
			this.dataForm.id = id || '';
			this.dataForm.templateId = modelId || '';
			this.getFormOperates();
			this.loading = true;
			this.dialogLoading = false;
			this.prevDis = false;
			this.nextDis = false;
			this.allList = allList || [];
			this.type = type;
			if(type === 3 || type === 5){
				this.showMoreBtn = false;
			}else{
				if(this.allList.length){
					this.index = this.allList.findIndex((item) => item.id === id);
					if(this.index === 0)this.prevDis = true;
					if(this.index === this.allList.length - 1)this.nextDis = true;
				}else{
					this.prevDis = true;
					this.nextDis = true;
				}
			}

			this.$nextTick(() => {
				if(this.dataForm.id){
					magic.core
						.service({
							url:'/api/form/instance/data',
							method:'get',
							params:{
								templateId:this.dataForm.templateId,
								id:this.dataForm.id,
							},
						})
						.then(({data}) => {
							console.log(data, '====data===========');

							this.dataForm.data = data.data;
							if(!this.dataForm.data) return;
							this.formData = {...this.dataForm.data, id:this.dataForm.id};
							this.fillFormData(this.formConf, this.formData);
							this.dialogLoading = true;
							this.$nextTick(() => {
								this.visible = true;
								this.loading = false;
							});
						});
				}else{
					this.formData = {};
					this.fillFormData(this.formConf, this.formData, 'add');
					this.dialogLoading = true;
					this.$nextTick(() => {
						this.visible = true;
						this.loading = false;
					});
				}
				this.key = +new Date();
			});
		},
		prev(){
			this.index--;
			if(this.index === 0)this.prevDis = true;
			this.nextDis = false;
			this.renewModelInfo();
		},
		next(){
			this.index++;
			if(this.index === this.allList.length - 1)this.nextDis = true;
			this.prevDis = false;
			this.renewModelInfo();
		},
		renewModelInfo(){
			magic.core
				.service({
					url:'/api/form/instance/data',
					method:'get',
					params:{
						templateId:this.modelId,
						id:this.allList[this.index].id,
					},
				})
				.then(({data}) => {
					this.dataForm.data = data;
					this.dataForm.id = data.id;
					if(!this.dataForm.data) return;
					this.formData = {...this.dataForm.data, id:this.dataForm.id};
					this.fillFormData(this.formConf, this.formData);
					this.$nextTick(() => {
						this.key = +new Date();
					});
				});
		},
		getFormOperates(){
			if(this.isPreview || !this.useFormPermission) return;
			const permissionList = this.$store.getters.permissionList;
			const modelId = this.$route.meta.modelId;
			const list = permissionList.filter((o) => o.modelId === modelId);
			this.formOperates = list[0] && list[0].form ? list[0].form : [];
		},
		fillFormData(form, data, flag){
			const loop = (list, parent) => {
				list.forEach((item) => {
					if(item.model){
                        // 获取初始值，如果 data 中不存在则使用默认值
						let val = Object.prototype.hasOwnProperty.call(data, item.model)
							? data[item.model]
							: item.config.defaultValue;

                        // 新增模式或子表处理特殊默认值
						if(flag === 'add' || item.config.isSubTable){
							//设置默认当前时间/组织/部门/用户时
							//TODO 待联调
							if(item.config.defaultCurrent){
								const identity = item.config.identity;
								switch(identity){
									case 'date':
										val = dayjs().format(item.format.replace('yyyy', 'YYYY').replace('dd', 'DD'));
										break;
									case 'comSelect':
										// val = this.userInfo.organizeIdList instanceof Array
										// 	? (item.multiple ? [this.userInfo.organizeIdList] : this.userInfo.organizeIdList)
										// 	: [];
										break;
									case 'time':
										val = toDate(new Date(), item.format);
										break;
									case 'userSelect':
										// val = this.userInfo.userId;
										break;
									case 'depSelect':
										// val = this.userInfo.departmentId;
										break;
								}
							}
						}

                        // 更新字段默认值
						item.config.defaultValue = val;

                       // 根据权限设置显示状态
						if(!this.isPreview && this.useFormPermission){
							const id = item.config.isSubTable ? `${parent.model}-${item.model}` : item.model;
							const noShow = item.hidden || !(this.formOperates?.some((o) => o.enCode === id));
							this.$set(item.config, 'noShow', noShow);
						}
					}

                   // 递归处理子项
					if(item.config?.children && Array.isArray(item.config.children)){
						loop(item.config.children, item);
					}
				});
			};

			loop(form.fields);
			form.formData = data;
		},

		resetForm(){
			this.$nextTick(() => {
				this.$refs.dynamicForm && this.$refs.dynamicForm.resetForm();
			});
		},
		submitForm(data, callback, type){
			if(!data) return;
			if(type === 2){
				this.refreshDataList = true;
				this.continueBtnLoading = true;
			}else{
				this.btnLoading = true;
			}
			const formData = {...this.formData, ...data};
			// for(const key in formData){
			// 	if(key.includes('.')){
			// 		delete formData[key];
			// 	}
			// }
			this.dataForm.data = formData;
			magic.core
				.service({
					url:'/api/form/instance',
					method:this.dataForm.id ? 'put' : 'post',
					data:this.dataForm,
				})
				.then((res) => {
					//TODO 数据结构待验证
					if(this.dataForm.id){
						this.$message({
							message:res.message,
							type:'success',
							duration:1500,
							onClose:() => {
								if(callback && typeof callback === 'function') callback();
								this.$nextTick(() => {
									if(type === 2){
                    // getModelInfo(this.modelId, this.dataForm.id).then((res) => {
                    // 	this.dataForm = res.data;
                    // 	this.continueBtnLoading = false;
                    // 	if(!this.dataForm.data) return;
                    // 	this.formData = {
                    // 		...JSON.parse(this.dataForm.data),
                    // 		id:this.dataForm.id,
                    // 	};
                    // 	this.fillFormData(this.formConf, this.formData);
                    // });
									}else{
										this.visible = false;
										this.destroyStyle();
										this.btnLoading = false;
										this.$emit('refresh-data-list', true);
									}
								});
							},
						});
					}else{
						this.$message({
							message:res.message,
							type:'success',
							duration:1500,
							onClose:() => {
								if(callback && typeof callback === 'function') callback();
								this.$nextTick(() => {
									this.continueBtnLoading = false;
									if(type === 2){
										this.resetForm();
										this.$nextTick(() => {
											this.key = +new Date();
										});
										return;
									}
									this.visible = false;
									this.btnLoading = false;
									this.$emit('refresh-data-list', true);
								});
							},
						});
					}
					this.continueBtnLoading = false;
				})
				.catch(() => {
					this.continueBtnLoading = false;
					this.btnLoading = false;
				});
		},
		dataFormSubmit(type){
			if(this.isPreview){
				return this.$message({message:'功能预览不支持数据保存', type:'warning'});
			}
			this.$refs.dynamicForm && this.$refs.dynamicForm.submitForm(type);
		},
		destroyStyle(){
			if(document.getElementById('styleId')){
				document.getElementById('styleId').remove();
			}
		},
	},
};
</script>
<style lang="scss" scoped>
.previous-button {
    position: absolute;
    left: 20px;
}
</style>